package com.jstyle.jclife.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.GroundOverlayOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TileOverlay;
import com.jstyle.jclife.R;
import com.jstyle.jclife.utils.PathSmoothTool;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.WeakDataHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TrackHistoryActivity extends BaseActivity implements AMap.OnMapLoadedListener, com.jstyle.jclife.view.SportTrackView.DrawListener {

    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.mapRecordDetail)
    MapView mapRecordDetail;
    @BindView(R.id.SportTrackView)
    com.jstyle.jclife.view.SportTrackView SportTrackView;
    private AMap mAMap;
    private final static int AMAP_LOADED = 2;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
                    //useOMCMap();
                    setupRecord();
                    break;
                default:
                    break;
            }
        }
    };
    private TileOverlay mtileOverlay;
    private List<LatLng> pathoptimizeList;


    private Polyline mOriginPolyline;
    private Marker mOriginStartMarker;
    private Marker mOriginEndMarker;
    private List<LatLng> mOriginLatLngList;

    private void setupRecord() {
        if (mOriginLatLngList == null || mOriginLatLngList.size() == 0) return;
        PathSmoothTool mpathSmoothTool = new PathSmoothTool();
        mpathSmoothTool.setIntensity(4);
        pathoptimizeList = mpathSmoothTool.pathOptimize(mOriginLatLngList);
      //  pathoptimizeList =mOriginLatLngList;


        if (pathoptimizeList.size() == 0) return;

        drawPath();


    }
    private void drawPath(){
        try {

            mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(getBounds(),
                    50), new AMap.CancelableCallback() {
                @Override
                public void onFinish() {
                    Log.i(TAG, "onFinish: ");
                    List<Point> pointList = new ArrayList<>();
                    for (LatLng latLng : pathoptimizeList) {
                        pointList.add(mAMap.getProjection().toScreenLocation(latLng));
                    }
                    SportTrackView.setPathData(pointList);
                }

                @Override
                public void onCancel() {

                }
            });



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private int[] colorList = { 0xFF7DFF00,0xFFE1E618,0xFFFBE01C,  0xfff55638 };
    private void addOriginTrace(
            final List<LatLng> originList) {
        LatLng startLatLng = pathoptimizeList.get(0);
        LatLng endLatLng = pathoptimizeList.get(pathoptimizeList.size() - 1);
        int color=Color.GREEN;
        int color2=Color.parseColor("#f4c22b");
        int color3=Color.parseColor("#f55638");
        List<Integer>listColor=new ArrayList<>();
        float size=originList.size();
        int blendCorlor=0;
        Log.i(TAG, "addOriginTrace: ");
        for(int i=0;i<originList.size();i++){
            blendCorlor=color;
            if(i==0){

            }else{
                LatLng latLngLast=originList.get(i-1);
                LatLng latLng=originList.get(i);
                double distance= AMapUtils.calculateLineDistance(latLngLast,latLng);
                Log.i(TAG, "addOriginTrace: "+distance);
                if(distance<4){
                    blendCorlor = colorList[0];
                }else if(distance<=8){
                    blendCorlor =colorList[1];
                }else if(distance<=12){
                    blendCorlor=colorList[2];
                }else {
                    blendCorlor=colorList[3];
                }

            }

            listColor.add(blendCorlor);
        }
//        mAMap.addPolygon(new PolygonOptions()
//                .addAll(createRectangle(startLatLng,10,10)).fillColor(Color.parseColor("#2f000000")).strokeWidth(1));

        mOriginPolyline = mAMap.addPolyline(new PolylineOptions()
                .width(ScreenUtils.dip2px(this,6)).color(
                        Color.GREEN).addAll(originList).useGradient(false).colorValues(listColor));
        mOriginStartMarker = mAMap.addMarker(new MarkerOptions().position(
                startLatLng).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.start)));
        mOriginEndMarker = mAMap.addMarker(new MarkerOptions().position(
                endLatLng).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.end)));
        mAMap.addGroundOverlay(new GroundOverlayOptions().transparency(0.7f)
                .position(endLatLng, 2*1000*1000, 2*1000*1000)
                .image(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(this.getResources(), R.drawable.ic_marker_bg))));




    }

    private static final String TAG = "TrackHistoryActivity";
    private LatLngBounds getBounds() {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (mOriginLatLngList == null) {
            return b.build();
        }
        for (int i = 0; i < mOriginLatLngList.size(); i++) {
            b.include(mOriginLatLngList.get(i));
        }
        return b.build();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track_history);
        ButterKnife.bind(this);
        // MapsInitializer.loadWorldGridMap(true);
        mapRecordDetail.onCreate(savedInstanceState);
        btGoalBack.setText(R.string.Track_history);
        ScreenUtils.setTitleTypeface(btGoalBack);
        init();
    }

    private void init() {
        if (mAMap == null) {
            mAMap = mapRecordDetail.getMap();
            mAMap.setOnMapLoadedListener(this);
            Locale locale = getResources().getConfiguration().locale;
            String language = locale.getLanguage();
            mAMap.setMapLanguage(language);
        }
        mOriginLatLngList = WeakDataHolder.getInstance().getData();
        SportTrackView.setDrawListener(this);
        mAMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                if(SportTrackView.getVisibility()==View.VISIBLE){
                    SportTrackView.setVisibility(View.GONE);
                    addOriginTrace(pathoptimizeList);
                }

            }
        });
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapRecordDetail.onDestroy();
    }

    @Override
    public void onMapLoaded() {
        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
    }

    @OnClick({R.id.iv_back, R.id.iv_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                mAMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
                    @Override
                    public void onMapScreenShot(Bitmap bitmap) {

                    }

                    @Override
                    public void onMapScreenShot(Bitmap bitmap, int i) {
                        ScreenUtils.shareFile(TrackHistoryActivity.this, bitmap);
                    }
                });
                break;
        }
    }
    private List<LatLng> createRectangle(LatLng center, double halfWidth,
                                         double halfHeight) {
        List<LatLng> latLngs = new ArrayList<LatLng>();
        latLngs.add(new LatLng(center.latitude - halfHeight, center.longitude - halfWidth));
        latLngs.add(new LatLng(center.latitude - halfHeight, center.longitude + halfWidth));
        latLngs.add(new LatLng(center.latitude + halfHeight, center.longitude + halfWidth));
        latLngs.add(new LatLng(center.latitude + halfHeight, center.longitude - halfWidth));
        return latLngs;
    }

    @Override
    public void onDrawFinished() {
        if(SportTrackView.getVisibility()==View.VISIBLE){
            SportTrackView.setVisibility(View.GONE);
            addOriginTrace(mOriginLatLngList);
        }
    }
}
